import React from 'react';

const fetch = (url, opts = {}, onProgress) =>
    new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(opts.method || 'GET', url);
        Object.keys(opts.headers || {}).forEach(key => {
            xhr.setRequestHeader(key, opts.headers[key]);
        });
        xhr.onload = e => {
            const {
                target: { responseText, status }
            } = e;
            resolve({
                text: () => responseText,
                json: () => JSON.parse(responseText) || {},
                status
            });
        };
        xhr.onerror = reject;
        if (xhr.upload && onProgress) {
            xhr.upload.onprogress = e => {
                const { loaded, total } = e;
                onProgress(Math.round((loaded / total) * 100));
            };
        }
        xhr.send(opts.body);
    });

export default () => {
    const [uploadProgress, setUploadProgress] = React.useState(0);

    // 上传至服务器
    const uploadToServer = (url, file, config = {}) => {
        const { onProgress } = config;
        const options = {
            method: 'PUT',
            body: file,
            headers: {
                'Content-Type': 'application/octet-stream'
            }
        };
        const remoteUrl = !url.includes('https') ? url.replace('http', 'https') : url;

        return fetch(remoteUrl, options, progress => {
            if (onProgress) onProgress(progress);
            setUploadProgress(progress);
        });
    };

    const upload = async (file, config = {}) => {
        const { ossType = 'public' } = config; // private拿到key，无法直接使用，public拿到url
        let result = '';
        let response = '';
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        };

        // 考虑做下兼容
        if (ossType === 'private') {
            response = await fetch('/api/resource/public/oss/producePutPreSignUrls', {
                ...options,
                body: JSON.stringify({ sysCode: 'OA', fileNames: [file.name] })
            });
        } else {
            response = await fetch('/api/resource/public/oss/v2/produceputpresignurls', {
                ...options,
                body: JSON.stringify({ richText: '1', fileNames: [file.name] })
            });
        }

        const { data: signResult, code } = response.json();
        if (code === 10000) {
            const { preUrl } = signResult[0];
            // result = url;
            const ossResponse = await uploadToServer(preUrl, file, config);
            const { status } = ossResponse;
            if (status === 200) {
                // 🤮
                result = ossType === 'private' ? signResult[0].keyName : signResult[0].url;
            }
        } else {
            console.error('上传错误');
        }
        return result;
    };

    return [upload, uploadProgress];
};
